import { createContext, useContext, useState, useEffect, ReactNode } from 'react';

type Language = 'en' | 'zh';

interface LanguageContextType {
  language: Language;
  setLanguage: (lang: Language) => void;
  t: (key: string) => string;
}

const LanguageContext = createContext<LanguageContextType | undefined>(undefined);

// 翻译文本
const translations = {
  en: {
    home: 'Home',
    shop: 'Shop',
    categories: 'Categories',
    about: 'About',
    contact: 'Contact',
    search: 'Search',
    cart: 'Cart',
    user: 'User',
    userProfile: 'User Profile',
    profile: 'Profile',
    orders: 'Orders',
    settings: 'Settings',
    personalInformation: 'Personal Information',
    save: 'Save',
    saveChanges: 'Save Changes',
    cancel: 'Cancel',
    login: 'Login',
    loginSubtitle: 'Welcome back! Please sign in to your account',
    email: 'Email',
    password: 'Password',
    passwordRequired: 'Password is required',
    passwordTooShort: 'Password must be at least 6 characters',
    loginFailed: 'Invalid email or password',
    loginError: 'An error occurred during login',
    loggingIn: 'Logging in...',
    noAccount: 'Don\'t have an account?',
    registerNow: 'Register now',
    loginAgreement: 'By logging in, you agree to our',
    termsOfService: 'Terms of Service',
    privacyPolicy: 'Privacy Policy',
    forgotPassword: 'Forgot password?',
    register: 'Register',
    registerSubtitle: 'Create a new account to get started',
    fullName: 'Full Name',
    confirmPassword: 'Confirm Password',
    confirmPasswordRequired: 'Please confirm your password',
    passwordMismatch: 'Passwords do not match',
    registrationError: 'An error occurred during registration',
    registering: 'Registering...',
    haveAccount: 'Already have an account?',
    loginNow: 'Login now',
    byRegistering: 'By registering, you agree to our',
    yourNamePlaceholder: 'Enter your full name',
    passwordPlaceholder: 'Enter your password',
    confirmPasswordPlaceholder: 'Confirm your password',
    orderHistory: 'Order History',
    yourOrderHistory: 'Your order history and details',
    orderNumber: 'Order Number',
    viewDetails: 'View Details',
    noOrdersFound: 'No orders found',
    noOrdersDescription: 'You haven\'t placed any orders yet',
    continueShopping: 'Continue Shopping',
    passwordSettings: 'Password Settings',
    updatePassword: 'Update Password',
    currentPassword: 'Current Password',
    newPassword: 'New Password',
    notificationSettings: 'Notification Settings',
    emailNotifications: 'Email Notifications',
    receiveEmailUpdates: 'Receive updates on your orders and exclusive offers',
    smsNotifications: 'SMS Notifications',
    receiveSmsUpdates: 'Receive SMS alerts for your order status',
    promotionalOffers: 'Promotional Offers',
    receiveSpecialOffers: 'Get notified about special offers and discounts',
    
    // Shop page translations
    shopTitle: 'Hardware Products',
    shopSubtitle: 'Professional tools and hardware supplies for professionals and DIY enthusiasts',
    shopHeroAlt: 'Hardware tools display in our store',
    allCategories: 'All Categories',
    noProductsFound: 'No products found',
    tryDifferentCategory: 'Try selecting a different category',
    
    // Categories page translations
    categoriesTitle: 'Hardware Categories',
    categoriesSubtitle: 'Explore our hardware categories to find the tools you need',
    categoriesHeroAlt: 'Hardware tools categories display',
    handTools: 'Hand Tools',
    powerTools: 'Power Tools',
    measuringTools: 'Measuring Tools',
    fasteners: 'Fasteners',
    electricalSupplies: 'Electrical Supplies',
    plumbingSupplies: 'Plumbing Supplies',
    handToolsDesc: 'Professional-grade hand tools for every application',
    powerToolsDesc: 'Cordless and electric power tools for construction and renovation',
    measuringToolsDesc: 'Precision measuring instruments for accurate work',
    fastenersDesc: 'Screws, nuts, bolts and other fastening solutions',
    electricalSuppliesDesc: 'Wiring, connectors and electrical accessories',
    plumbingSuppliesDesc: 'Fittings, pipes and plumbing accessories',
    productsCount: '{{count}} Products',
    explore: 'Explore',
    
    // About page translations
    aboutTitle: 'About Our Hardware Store',
    aboutSubtitle: 'Providing quality tools and hardware supplies since 2005',
    aboutHeroAlt: 'Our team of hardware experts',
    ourStory: 'Our Story',
    storyParagraph1: 'Founded in 2005, our hardware store started with a simple mission: to provide professional-grade tools and hardware supplies to both professionals and DIY enthusiasts.',
    storyParagraph2: 'What began as a small local store has grown into a trusted online retailer serving customers nationwide with quality products and expert advice.',
    storyParagraph3: 'We carefully select each product for quality and durability, partnering with leading manufacturers to bring you the best tools at competitive prices.',
    countriesServed: 'Cities Served',
    happyCustomers: 'Happy Customers',
    products: 'Products',
    ourJourney: 'Our Journey',
    journeySubtitle: 'Key milestones in our development as a hardware supplier',
    milestone2015: 'Company founded with focus on hand tools and fasteners',
    milestone2017: 'Expanded product line to include power tools and electrical supplies',
    milestone2019: 'Launched online store and nationwide shipping',
    milestone2021: 'Introduced professional contractor services and bulk ordering',
    milestone2023: 'Expanded warehouse and distribution network',
    ourTeam: 'Our Team',
    teamSubtitle: 'Meet our hardware experts and tool specialists',
    ceo: 'Founder & CEO',
    cto: 'Operations Director',
    cfo: 'Purchasing Manager',
    cmo: 'Customer Service Director',
    yearsExperience: 'Years Experience',
    warehouseAlt: 'Our tool warehouse',
    
    // Contact page translations
    contactTitle: 'Contact Us',
    contactSubtitle: 'Have questions about our tools or need expert advice? We\'d love to hear from you',
    contactHeroAlt: 'Our customer service team',
    sendUsMessage: 'Send Us a Message',
    yourName: 'Your Name',
    emailAddress: 'Email Address',
    subject: 'Subject',
    yourMessage: 'Your Message',
    sendMessage: 'Send Message',
    sending: 'Sending...',
    messageSentSuccess: 'Your message has been sent successfully!',
    messageSentError: 'There was an error sending your message. Please try again.',
    contactInformation: 'Contact Information',
    ourLocation: 'Our Location',
    phoneNumber: 'Phone Number',
    emailUs: 'Email Us',
    workingHours: 'Working Hours',
    mondayFriday: 'Monday - Friday',
    saturday: 'Saturday',
    followUs: 'Follow Us',
    newsletter: 'Newsletter',
    yourEmail: 'Your email',
    
    // Shared translations
    heroTitle: 'Professional Hardware Tools & Supplies',
    heroSubtitle: 'Quality tools for professionals and DIY enthusiasts with expert advice and support',
    shopNow: 'Shop Now',
    exploreCategories: 'Explore Categories',
    scrollToExplore: 'Scroll to explore',
    
    featureTitle: 'Why Choose Our Hardware Store',
    featureSubtitle: 'Professional-grade tools and supplies with expert support',
    freeShipping: 'Free Shipping on Orders Over $99',
    freeShippingDesc: 'We ship to all locations within mainland China with free shipping on qualifying orders',
    securePayment: 'Secure Payment',
    securePaymentDesc: '100% secure payment processing with multiple payment options',
    customerSupport: 'Expert Advice',
    customerSupportDesc: 'Our team of hardware specialists is available to help you select the right tools',
    easyReturns: '30-Day Returns',
    easyReturnsDesc: 'Return any unused tools within 30 days for a full refund',
    
    featuredProducts: 'Featured Tools',
    featuredProductsSubtitle: 'Our handpicked selection of professional-grade hardware tools. Each tool is selected for quality and performance.',
    viewAllProducts: 'View All Products',
    
    testimonialsTitle: 'Customer Reviews',
    testimonialsSubtitle: 'Feedback from professional contractors and DIY enthusiasts',
    
    companyInfo: 'Company Info',
    quickLinks: 'Quick Links',
    customerService: 'Customer Service',
    contactUs: 'Contact Us',
    subscribeNewsletter: 'Subscribe to Our Newsletter',
    newsletterPlaceholder: 'Your email address',
    subscribe: 'Subscribe',
    copyright: `© ${new Date().getFullYear()} ProHardware. All rights reserved.`,
    
    
     product1Name: 'Magnetic Screwdriver Set',
     product1Desc: '12-piece professional screwdriver set with magnetic tips, ergonomic handles, and chrome vanadium steel shafts for maximum durability',
     product2Name: '20V Cordless Power Drill',
     product2Desc: '20V lithium-ion cordless drill with variable speed control (0-1500 RPM), 25+1 torque settings, and built-in LED work light for dark areas',
    product3Name: 'Measuring Tape Set',
    product3Desc: '3-piece measuring tape set with metric and imperial units, shock-resistant case',
    product4Name: 'Heavy Duty Wrench Set',
    product4Desc: '8-piece adjustable wrench set with forged steel construction and lifetime warranty',
     product5Name: 'Chrome Vanadium Socket Wrench Set',
     product5Desc: '24-piece socket wrench set with quick-release ratchet handle and storage case, including both metric and imperial sizes',
     product6Name: 'Fiberglass Handle Hammer Set',
     product6Desc: 'Professional grade claw hammer and ball-peen hammer set with non-slip rubber grips and shock-absorbing fiberglass handles',
     product7Name: 'Digital Level Tool',
     product7Desc: '9-inch aluminum level with magnetic strip, three vials, and digital display for precise measurements up to 0.1° accuracy',
     product8Name: 'Heavy Duty Pliers Set',
     product8Desc: '5-piece professional pliers set including combination, long nose, diagonal cutting, needle nose, and groove joint pliers with comfort grip handles',
    
    testimonial1: 'The quality of these tools is exceptional. As a professional contractor, I rely on my tools daily and these have exceeded my expectations.',
    testimonial2: 'Great selection of hardware supplies and excellent customer service. They helped me find exactly what I needed for my home renovation.',
    testimonial3: 'I\'ve been a DIY enthusiast for years and these are the best quality tools I\'ve ever owned. Worth every penny.',
    
    // Product detail page translations
    productNotFound: 'Product not found',
    loading: 'Loading...',
    zoomImage: 'Zoom image',
    backToShop: 'Back to Shop',
    details: 'Details',
    features: 'Features',
    quantity: 'Quantity',
    decreaseQuantity: 'Decrease quantity',
    increaseQuantity: 'Increase quantity',
    wishlist: 'Add to wishlist',
    description: 'Description',
    specifications: 'Specifications',
    reviews: 'Reviews',
    detailedDescription: 'Detailed Description',
    detailedProductSection1: 'This professional-grade tool is designed for durability and performance in demanding work environments.',
    detailedProductSection2: 'Constructed from high-quality materials, it provides reliable service for both professionals and serious DIY enthusiasts.',
    detailedProductFeature1: 'Professional-grade construction',
    detailedProductFeature2: 'Ergonomic design for reduced fatigue',
    detailedProductFeature3: 'Precision manufacturing for accurate results',
    detailedProductFeature4: 'Lifetime warranty against defects',
    detailedProductSection3: 'Whether you\'re a professional contractor or a DIY enthusiast, this tool will provide years of reliable service.',
    relatedProducts: 'Related Products',
    viewProductDetails: 'View Details',
    feature1: 'Material',
    feature1Value: 'Chrome-vanadium steel construction',
    feature2: 'Handle',
    feature2Value: 'Ergonomic rubber grip with anti-slip design',
    feature3: 'Tips',
    feature3Value: 'Magnetic tips for easy screw retention',
    feature4: 'Included Sizes',
    feature4Value: 'Phillips #0-#3, Slotted 3-8mm',
    feature5: 'Power',
    feature5Value: '20V lithium-ion battery',
    feature6: 'Torque',
    feature6Value: '45 Nm max torque with 20+1 torque settings',
    feature7: 'Speed',
    feature7Value: '0-550 RPM variable speed',
    feature8: 'Chuck Size',
    feature8Value: '13mm keyless chuck',
    feature9: 'Lengths',
    feature9Value: '3m, 5m and 8m measuring tapes',
    feature10: 'Accuracy',
    feature10Value: 'Class II accuracy (±3mm per 1m)',
    feature11: 'Blade',
    feature11Value: 'Nylon-coated steel blade for durability',
    feature12: 'Locking',
    feature12Value: 'Positive locking mechanism',
    feature13: 'Sizes',
    feature13Value: '6-24mm adjustable wrenches',
    feature14: 'Material',
    feature14Value: 'Drop-forged chrome vanadium steel',
    feature15: 'Finish',
    feature15Value: 'Polished chrome finish resists corrosion',
    feature16: 'Warranty',
    feature16Value: 'Lifetime manufacturer warranty',
    detailedProduct1Desc: 'This professional screwdriver set includes 12 precision screwdrivers with magnetic tips to securely hold screws. The ergonomic handles reduce hand fatigue during extended use, while the chrome-vanadium steel shafts provide maximum strength and durability. Each screwdriver features a color-coded handle for easy identification of tip type and size.',
    detailedProduct2Desc: 'Our cordless power drill delivers professional performance with its 20V lithium-ion battery. The variable speed control allows for precise drilling and driving, while the 20+1 torque settings let you adjust power for different materials. The built-in LED work light illuminates dark work areas, and the lightweight design reduces user fatigue during extended use.',
    detailedProduct3Desc: 'This measuring tape set includes three essential lengths (3m, 5m, and 8m) to cover all your measuring needs. The nylon-coated steel blades resist abrasion and provide long-lasting durability. The shock-resistant cases protect the tapes from drops, while the positive locking mechanisms hold measurements securely. Both metric and imperial units are printed clearly for easy reading.',
    detailedProduct4Desc: 'Forged from high-quality chrome vanadium steel, this wrench set provides maximum strength and durability. The adjustable jaws feature precise measurement markings and can be easily adjusted to fit various nut and bolt sizes. The polished chrome finish resists corrosion, and the ergonomic handles provide a comfortable, non-slip grip even when wearing work gloves.',
    // Cart-related translations
    addedToCart: 'added to cart',
    removedFromCart: 'removed from cart',
    cartCleared: 'Cart cleared',
    viewCart: 'View Cart',
    yourCart: 'Your Shopping Cart',
    emptyCart: 'Your cart is empty',
    emptyCartDesc: 'Looks like you haven\'t added any tools to your cart yet.',
    startShopping: 'Start Shopping',
    product: 'Product',
    price: 'Price',
    subtotal: 'Subtotal',
    total: 'Total',
    remove: 'Remove',
    clearCart: 'Clear Cart',
    checkout: 'Proceed to Checkout',
    itemTotal: '{{count}} items',
      itemTotalOne: '1 item',
      tax: 'Tax',
      included: 'Included',
      calculatedAtCheckout: 'Calculated at Checkout',
    mapAlt: 'Map showing shipping areas',
    // Cart specific translations
    steelChoice: 'Steel Type',
    steelType: 'Chrome Vanadium',
    toolWarranty: 'Tool Warranty',
    withWarranty: 'Lifetime Warranty',
    orderInstructions: 'Order instructions',
     securePayments: '100% Secure Payments',
       orderSummary: 'Order Summary',
      // Payment page translations
      paymentSuccess: 'Payment successful',
      paymentFailed: 'Payment failed',
      paymentError: 'An error occurred with your payment',
      checkoutProcess: 'Checkout',
      completeOrderPayment: 'Complete your order and payment information',
      shippingInformation: 'Shipping Information',
      paymentMethod: 'Payment Method',
      creditCard: 'Credit Card',
      paypal: 'PayPal',
      bankTransfer: 'Bank Transfer',
      cardNumber: 'Card Number',
      expiryDate: 'Expiry Date',
      cvv: 'CVV',
      placeOrder: 'Place Order',
      processing: 'Processing...',
      phone: 'Phone',
      address: 'Address',
      city: 'City',
      zipCode: 'ZIP Code',
      country: 'Country',
      nameRequired: 'Name is required',
      emailRequired: 'Email is required',
      invalidEmail: 'Please enter a valid email',
      phoneRequired: 'Phone number is required',
      addressRequired: 'Address is required',
      cityRequired: 'City is required',
      zipCodeRequired: 'ZIP code is required',
      countryRequired: 'Country is required',
      securePaymentGuarantee: 'Secure Payment',
      paymentGuarantee: 'Your payment information is encrypted and secure',
      free: 'Free'
  },
  zh: {
    home: '首页',
    shop: '商店',
    categories: '分类',
    about: '关于我们',
    contact: '联系我们',
    search: '搜索',
    cart: '购物车',
    user: '用户',
    
    // Shop page translations
    shopTitle: '五金工具',
    shopSubtitle: '专业工具和五金用品，适合专业人士和DIY爱好者',
    shopHeroAlt: '我们商店的五金工具展示',
    allCategories: '全部分类',
    noProductsFound: '未找到产品',
    tryDifferentCategory: '尝试选择其他分类',
    
    // Categories page translations
    categoriesTitle: '五金分类',
    categoriesSubtitle: '浏览我们的五金分类，找到您需要的工具',
    categoriesHeroAlt: '五金工具分类展示',
    handTools: '手动工具',
    powerTools: '电动工具',
    measuringTools: '测量工具',
    fasteners: '紧固件',
    electricalSupplies: '电气用品',
    plumbingSupplies: ' plumbing用品',
    handToolsDesc: '适用于各种应用的专业级手动工具',
    powerToolsDesc: '用于建筑和装修的无绳和电动工具',
    measuringToolsDesc: '用于精确工作的精密测量仪器',
    fastenersDesc: '螺丝、螺母、螺栓和其他紧固解决方案',
    electricalSuppliesDesc: '电线、连接器和电气配件',
    plumbingSuppliesDesc: '配件、管道和 plumbing配件',
    productsCount: '{{count}} 件产品',
    explore: '探索',
    
    // About page translations
    aboutTitle: '关于我们的五金店',
    aboutSubtitle: '自2005年以来提供优质工具和五金用品',
    aboutHeroAlt: '我们的五金专家团队',
    ourStory: '我们的故事',
    storyParagraph1: '我们的五金店成立于2005年，最初的使命很简单：为专业人士和DIY爱好者提供专业级工具和五金用品。',
    storyParagraph2: '从一家小型本地商店发展成为值得信赖的在线零售商，为全国客户提供优质产品和专业建议。',
    storyParagraph3: '我们精心挑选每种产品，注重质量和耐用性，与领先制造商合作，为您带来最优质的工具，价格具有竞争力。',
    countriesServed: '服务城市',
    happyCustomers: '满意客户',
    products: '产品数量',
    ourJourney: '我们的历程',
    journeySubtitle: '我们作为五金供应商发展的关键里程碑',
    milestone2015: '公司成立，专注于手动工具和紧固件',
    milestone2017: '扩大产品线，包括电动工具和电气用品',
    milestone2019: '推出在线商店和全国配送',
    milestone2021: '推出专业承包商服务和批量订购',
    milestone2023: '扩大仓库和配送网络',
    ourTeam: '我们的团队',
    teamSubtitle: '认识我们的五金专家和工具专家',
    ceo: '创始人兼首席执行官',
    cto: '运营总监',
    cfo: '采购经理',
    cmo: '客户服务总监',
    yearsExperience: '年经验',
    warehouseAlt: '我们的工具仓库',
    
    // Contact page translations
    contactTitle: '联系我们',
    contactSubtitle: '对我们的工具有疑问或需要专业建议？我们很乐意听取您的意见',
    contactHeroAlt: '我们的客户服务团队',
    sendUsMessage: '给我们发消息',
    yourName: '您的姓名',
    emailAddress: '电子邮箱',
    subject: '主题',
    yourMessage: '您的消息',
    sendMessage: '发送消息',
    sending: '发送中...',
    messageSentSuccess: '您的消息已成功发送！',
    messageSentError: '发送消息时出错。请重试。',
    contactInformation: '联系信息',
    ourLocation: '我们的位置',
    phoneNumber: '电话号码',
    emailUs: '给我们发邮件',
    workingHours: '工作时间',
    mondayFriday: '周一至周五',
    saturday: '周六',
    followUs: '关注我们',
    newsletter: '新闻通讯',
    yourEmail: '您的邮箱',
    
    // Shared translations
    heroTitle: '专业五金工具和用品',
    heroSubtitle: '为专业人士和DIY爱好者提供优质工具，提供专业建议和支持',
    shopNow: '立即购买',
    exploreCategories: '浏览分类',
    scrollToExplore: '向下滚动探索',
    
    featureTitle: '为什么选择我们的五金店',
    featureSubtitle: '专业级工具和用品，提供专业支持',
    freeShipping: '满99元免费送货',
    freeShippingDesc: '我们发货到中国大陆所有地区，符合条件的订单免费送货',
    securePayment: '安全支付',
    securePaymentDesc: '100%安全支付处理，多种支付方式',
    customerSupport: '专业建议',
    customerSupportDesc: '我们的五金专家团队可以帮助您选择合适的工具',
    easyReturns: '30天退货',
    easyReturnsDesc: '30天内退回任何未使用的工具，全额退款',
    
    featuredProducts: '精选工具',
    featuredProductsSubtitle: '我们精心挑选的专业级五金工具。每种工具都经过质量和性能选择。',
    viewAllProducts: '查看全部产品',
    
    testimonialsTitle: '客户评价',
    testimonialsSubtitle: '来自专业承包商和DIY爱好者的反馈',
    
    companyInfo: '公司信息',
    quickLinks: '快速链接',
    customerService: '客户服务',
    contactUs: '联系我们',
    subscribeNewsletter: '订阅我们的新闻通讯',
    newsletterPlaceholder: '您的电子邮箱',
    subscribe: '订阅',
    copyright: `© ${new Date().getFullYear()} 专业五金。保留所有权利。`,
    
    
      product1Name: '磁性螺丝刀套装',
      product1Desc: '12件套专业螺丝刀套装，带磁性尖端、人体工学手柄和铬钒钢轴，确保最大耐用性',
      "6PieceSet": '6件套装',
      "12PieceSet": '12件套装',
      "24PieceSet": '24件套装',
      batteryCapacity: '电池容量',
      "1.5AhBattery": '1.5Ah',
      "3.0AhBattery": '3.0Ah',
      length: '卷尺长度',
      "3Meters": '3米',
      "5Meters": '5米',
      "8Meters": '8米',
     product7Name: '数显水平仪',
     product7Desc: '9英寸铝制水平仪，带磁条、三个水准泡和数字显示屏，精度可达0.1°',
     product8Name: '重型钳子套装',
     product8Desc: '5件套专业钳子，包括组合钳、尖嘴钳、斜口钳、针鼻钳和沟槽接头钳，带舒适握把',
    
    testimonial1: '这些工具的质量非常出色。作为专业承包商，我每天都依赖我的工具，这些工具超出了我的期望。',
    testimonial2: '五金用品种类繁多，客户服务出色。他们帮助我找到了家庭装修所需的确切物品。',
    testimonial3: '多年来我一直是DIY爱好者，这些是我拥有过的最优质的工具。物有所值。',
    
    // Product detail page translations
    productNotFound: '未找到产品',
    loading: '加载中...',
    zoomImage: '放大图片',
    backToShop: '返回商店',
    details: '详情',
    features: '特性',
    quantity: '数量',
    decreaseQuantity: '减少数量',
    increaseQuantity: '增加数量',
    wishlist: '加入愿望清单',
    description: '描述',
    specifications: '规格',
    reviews: '评价',
    detailedDescription: '详细描述',
    detailedProductSection1: '这款专业级工具专为苛刻的工作环境中的耐用性和性能而设计。',
    detailedProductSection2: '采用高品质材料制造，为专业人士和认真的DIY爱好者提供可靠的服务。',
    detailedProductFeature1: '专业级结构',
    detailedProductFeature2: '人体工学设计，减少疲劳',
    detailedProductFeature3: '精密制造，确保准确结果',
    detailedProductFeature4: '终身保修，防止缺陷',
    detailedProductSection3: '无论您是专业承包商还是DIY爱好者，这款工具都将提供多年的可靠服务。',
    relatedProducts: '相关产品',
    viewDetails: '查看详情',
    feature1: '材质',
    feature1Value: '铬钒钢结构',
    feature2: '手柄',
    feature2Value: '人体工学橡胶握把，防滑设计',
    feature3: '尖端',
    feature3Value: '磁性尖端，便于螺丝固定',
    feature4: '包含尺寸',
    feature4Value: '十字#0-#3，一字3-8mm',
    feature5: '功率',
    feature5Value: '20V锂离子电池',
    feature6: '扭矩',
    feature6Value: '最大扭矩45 Nm，20+1扭矩设置',
    feature7: '速度',
    feature7Value: '0-550 RPM变速',
    feature8: '夹头尺寸',
    feature8Value: '13mm无钥匙夹头',
    feature9: '长度',
    feature9Value: '3m、5m和8m卷尺',
    feature10: '精度',
    feature10Value: 'II类精度（每1m±3mm）',
    feature11: '刀片',
    feature11Value: '尼龙涂层钢刀片，耐用',
    feature12: '锁定',
    feature12Value: '正向锁定机制',
    feature13: '尺寸',
    feature13Value: '6-24mm可调扳手',
    feature14: '材质',
    feature14Value: '锻造铬钒钢',
    feature15: '表面处理',
    feature15Value: '抛光镀铬表面，抗腐蚀',
    feature16: '保修',
    feature16Value: '终身制造商保修',
    detailedProduct1Desc: '这款专业螺丝刀套装包括12把精密螺丝刀，带磁性尖端，可牢固固定螺丝。人体工学手柄减少长时间使用时的手部疲劳，而铬钒钢轴提供最大强度和耐用性。每个螺丝刀都有彩色编码手柄，便于识别尖端类型和尺寸。',
    detailedProduct2Desc: '我们的无绳电钻凭借其20V锂离子电池提供专业性能。变速控制允许精确钻孔和驱动，而20+1扭矩设置让您可以调整不同材料的功率。内置LED工作灯照亮黑暗的工作区域，轻巧的设计减少长时间使用时的用户疲劳。',
    detailedProduct3Desc: '这款卷尺套装包括三种基本长度（3m、5m和8m），可满足您所有的测量需求。尼龙涂层钢刀片耐磨损，提供持久耐用性。防震外壳保护卷尺免受跌落，而正向锁定机制可牢固固定测量值。公制和英制单位都清晰印刷，便于阅读。',
    detailedProduct4Desc: '这款扳手套装由高品质铬钒钢锻造而成，提供最大强度和耐用性。可调钳口带有精确的测量标记，可以轻松调整以适应各种螺母和螺栓尺寸。抛光镀铬表面抗腐蚀，人体工学手柄即使戴工作手套也能提供舒适的防滑抓握。',
    // Cart-related translations
    addedToCart: '已添加到购物车',
    removedFromCart: '已从购物车移除',
    cartCleared: '购物车已清空',
    viewCart: '查看购物车',
    yourCart: '我的购物车',
    emptyCart: '购物车为空',
    emptyCartDesc: '看起来您还没有添加任何工具到购物车。',
    startShopping: '开始购物',
    product: '商品',
    price: '价格',
    subtotal: '小计',
    total: '总计',
    remove: '移除',
    clearCart: '清空购物车',
    checkout: '去结算',
     itemTotal: '{{count}}件商品',
      itemTotalOne: '1件商品',
         tax: '税费',
         included: '已包含',
        calculatedAtCheckout: '结账时计算',
     mapAlt: '显示配送区域的地图',
     // 购物车特定翻译
     steelChoice: '钢材类型',
     steelType: '铬钒钢',
     toolWarranty: '工具保修',
     withWarranty: '终身保修',
     orderInstructions: '订单说明',
      securePayments: '100%安全支付',
       orderSummary: '订单摘要',
      // Payment page translations
      paymentSuccess: '支付成功',
      paymentFailed: '支付失败',
      paymentError: '支付时发生错误',
      checkoutProcess: '结账',
      completeOrderPayment: '完成您的订单和支付信息',
      shippingInformation: '配送信息',
      paymentMethod: '支付方式',
      creditCard: '信用卡',
      paypal: '贝宝',
      bankTransfer: '银行转账',
      cardNumber: '卡号',
      expiryDate: '有效期',
      cvv: '安全码',
      placeOrder: '提交订单',
      processing: '处理中...',
      fullName: '全名',
      email: '电子邮箱',
      phone: '电话',
      address: '地址',
      city: '城市',
      zipCode: '邮政编码',
      country: '国家',
      nameRequired: '姓名为必填项',
      emailRequired: '电子邮箱为必填项',
      invalidEmail: '请输入有效的电子邮箱',
      phoneRequired: '电话号码为必填项',
      addressRequired: '地址为必填项',
      cityRequired: '城市为必填项',
      zipCodeRequired: '邮政编码为必填项',
      countryRequired: '国家为必填项',
      securePaymentGuarantee: '安全支付',
      paymentGuarantee: '您的支付信息已加密且安全',
       free: '免费',
       userProfile: '用户资料',
       profile: '个人资料',
       orders: '我的订单',
       settings: '账户设置',
       personalInformation: '个人信息',
       save: '保存',
       saveChanges: '保存更改',
       cancel: '取消',
       orderHistory: '订单历史',
       yourOrderHistory: '您的订单历史和详情',
       orderNumber: '订单编号',
        viewOrderDetails: '查看详情',
       noOrdersFound: '暂无订单',
       noOrdersDescription: '您还没有任何订单记录',
       continueShopping: '继续购物',
       passwordSettings: '密码设置',
       login: '登录',
        loginSubtitle: '欢迎回来！请登录您的账户',
       password: '密码',
       passwordRequired: '密码不能为空',
       passwordTooShort: '密码长度不能少于6个字符',
       loginFailed: '邮箱或密码错误',
       loginError: '登录过程中发生错误',
       loggingIn: '登录中...',
       noAccount: '没有账户？',
       registerNow: '立即注册',
       loginAgreement: '登录即表示您同意我们的',
       termsOfService: '服务条款',
       privacyPolicy: '隐私政策',
       forgotPassword: '忘记密码？',
       register: '注册',
        registerSubtitle: '创建新账户开始使用',
       confirmPassword: '确认密码',
       confirmPasswordRequired: '请确认您的密码',
       passwordMismatch: '密码不匹配',
       registrationError: '注册过程中发生错误',
       registering: '注册中...',
       haveAccount: '已有账户？',
       loginNow: '立即登录',
       byRegistering: '注册即表示您同意我们的',
       yourNamePlaceholder: '输入您的全名',
       passwordPlaceholder: '输入您的密码',
       confirmPasswordPlaceholder: '确认您的密码',
       updatePassword: '更新密码',
       currentPassword: '当前密码',
        newPassword: '新密码',
       notificationSettings: '通知设置',
       emailNotifications: '邮件通知',
       receiveEmailUpdates: '接收订单更新和独家优惠',
       smsNotifications: '短信通知',
       receiveSmsUpdates: '接收订单状态的短信提醒',
       promotionalOffers: '促销优惠',
        receiveSpecialOffers: '获取特别优惠和折扣通知',
        reviewsComingSoon: '评论功能即将上线'
  }
};

export function LanguageProvider({ children }: { children: ReactNode }) {
  // 从本地存储获取保存的语言，默认为英语
  const [language, setLanguage] = useState<Language>(() => {
    const savedLanguage = localStorage.getItem('language') as Language;
    return savedLanguage || 'en';
  });

  // 保存语言偏好到本地存储
  useEffect(() => {
    localStorage.setItem('language', language);
  }, [language]);

  // 切换语言
  const updateLanguage = (lang: Language) => {
    setLanguage(prev => lang);
  };

  // 翻译函数
  const t = (key: string, params?: Record<string, string | number>): string => {
    const translation = translations[language][key as keyof typeof translations.en] || key;
    
    if (!params) return translation;
    
    // Replace placeholders with parameter values
    return Object.entries(params).reduce((result, [param, value]) => {
      return result.replace(`{{${param}}}`, value.toString());
    }, translation);
  };

  return (
    <LanguageContext.Provider value={{ language, setLanguage: updateLanguage, t }}>
      {children}
    </LanguageContext.Provider>
  );
}

// 自定义hook方便组件使用
export function useLanguage() {
  const context = useContext(LanguageContext);
  if (context === undefined) {
    throw new Error('useLanguage must be used within a LanguageProvider');
  }
  return context;
}